package m.store.task;

import m.common.action.Action;
import m.common.model.util.ModelUpdate;
import m.common.model.util.QueryCondition;
import m.fun.model.AskInfo;
import m.system.db.TransactionManager;
import m.system.util.JSONMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

public class AskRemoveSaleSupport implements Runnable {
    private AskRemoveSaleSupport(){}
    private static boolean isRun=true;
    static Thread th;
    static final List<String> ls=new ArrayList<>();

    @Override
    public void run() {
        while (true){
            if(ls.isEmpty()){
                TransactionManager.closeConnection();
                LockSupport.park();
                TransactionManager.initConnection();
            }
            if(!isRun) break;
            if(!ls.isEmpty()){
                String saleOid=ls.remove(0);
                execute(saleOid);
            }
        }
    }
    private void execute(String saleOid){
        try {
            if(ls.size()<10) Thread.sleep(100L);
            ModelUpdate.init(AskInfo.class)
                .set("sale", null)
                .set("buildStatus", AskInfo.Build_No)
                .execute(QueryCondition.eq("sale.oid",saleOid));
        }catch (Exception e){
            Action.directLog("定时任务","更新询价出库冗余信息失败",this.getClass().getName(),
                    new JSONMessage().push("saleOid",saleOid).toJSONString(),e);
        }
    }
    /** 出库删除成功时调用
     * 出库oid
     */
    public static void add(String sale_oid){
        if(!ls.contains(sale_oid)) {
            ls.add(sale_oid);
        }
    }

    /**
     * 开始更新
     */
    public static void start(){
        if(null==th){
            th=new Thread(new AskRemoveSaleSupport());
            th.start();
        }else{
            LockSupport.unpark(th);
        }
    }

    public static void close(){
        isRun=false;
        LockSupport.unpark(th);
    }
}
